<template>
  <j-modal :title="title + $t('套餐')" :width="width" :visible="visible" switchFullscreen @cancel="handleCancel">
    <template slot="footer">
      <a-button @click="handleCancel" :disabled="confirmLoading">{{$t('取消')}}</a-button>
      <a-button @click="handleOk" type="primary" :disabled="confirmLoading">{{$t('保存')}}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div :disabled="formDisabled">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-row>
            <a-col :span="24">
              <a-form-model-item :label="$t('商品名称')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                <a-input v-model="model.name" :placeholder="$t('请输入商品名称')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('说明')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-textarea rows="2" v-model="model.comment" :placeholder="$t('请输入备注')" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('限购数量')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input-number v-model="model.limitNum" :disabled="limitCycledisable" :formatter="formatter"
                  :parser="parser"/>
                  <span style="color: #f2944b; margin-left: 10px;">{{$t('（每个会员最多可领取的数量，0表示不限制）')}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('包含卖品')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <span style="color: #f2944b">{{$t('该套餐中所包含的商品信息应该与抖音平台上架的此商品中的内容保持一致')}}</span>
                <a-table :columns="columns" :dataSource="dataSource" size="middle" bordered class="customTable" :pagination="false">
                  <template slot="action" slot-scope="text, record">
                    <a-icon type="close" @click="deleteGoods(text, record)" />
                  </template>
                  <template slot="select" slot-scope="text, record">
                    <a-select
                      v-model="record.goodsForm"
                      :placeholder="$t('请选择商品形态')"
                      @change="(val)=>handleFormChange(val,record)"
                      style="min-width: 200px"
                    >
                      <a-select-option v-for="good in addFormList" :key="good.value">{{ good.title }}</a-select-option>
                    </a-select>
                  </template>
                  <template slot="selectTwo" slot-scope="text, record">
                    <a-select
                      v-model="record.goodsId"
                      show-search
                      :placeholder="$t('请输入商品编码/名称')"
                      :filter-option="false"
                      :not-found-content="null"
                      @search="(val)=>handleGoodsSearch(record.goodsForm,val)"
                      :disabled="record.goodsForm == undefined"
                      style="min-width: 200px"
                    >
                      <a-select-option v-for="good in addGoodsList" :key="good.id">{{ good.name }}</a-select-option>
                    </a-select>
                  </template>
                  <template slot="inputNum" slot-scope="text, record">
                    <a-input-number v-model="record.amount"></a-input-number>
                  </template>
                </a-table>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import { getAction, httpAction } from '@/api/manage'
let _self
export default {
  name: 'GoodsModal',
  components: {},
  data() {
    return {
      title: '',
      width: 900,
      visible: false,
      model: {
        limitNum: 1,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      confirmLoading: false,
      validatorRules: {
        name: [{ required: true, message: this.$t('请输入商品名称') }],
      },
      url: {
        add: '/goods/bisThirdGoods/add',
        edit: '/goods/bisThirdGoods/edit',
        queryById: '/goods/bisThirdGoods/queryBisThirdGoodsPackageByMainId',
      },
      columns: [
        {
          title: '＋',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                lineHeight: 1,
                fontWeight: 'bold',
                cursor: 'pointer',
                padding:'0 8px'
              },
              on: {
                click: () => {
                  _self.addGoods()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                lineHeight: 1,
                fontWeight: 'bold',
                cursor: 'pointer',
                padding:'0 8px'
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
        {
          title: this.$t('商品形态'),
          dataIndex: 'form',
          align: 'center',
          width: 160,
          customCell: function (column) {
            return {
              style: {
                padding: '7px 8px'
              },
            }
          },
          scopedSlots: { customRender: 'select' },
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'name',
          align: 'center',
          width: 300,
          customCell: function (column) {
            return {
              style: {
                padding: '7px 8px'
              },
            }
          },
          scopedSlots: { customRender: 'selectTwo' },
        },
        {
          title: this.$t('数量'),
          key: 'num',
          dataIndex: 'num',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center'
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                padding: '7px 8px'
              },
            }
          },
          scopedSlots: { customRender: 'inputNum' },
        },
      ],
      dataSource: [],
      addFormList: [],
      addGoodsList: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    _self = this
  },
  methods: {
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.dataSource = []
      this.getFormList()
      this.getGoodsList()
      getAction('/goods/bisThirdGoods/queryBisThirdGoodsPackageByMainId', { id: record.id }).then((res) => {
        if (res.success) {
          this.dataSource = res.result
        }
      })
    },
    handleOk() {
      let that = this
      let param = {}
      let i = 0
      that.dataSource.forEach((col) => {
        if (col.goodsForm == undefined) {
          that.$message.warning(that.$t('请选择商品形态'))
          return
        }
        if (col.goodsId == undefined) {
          that.$message.warning(that.$t('请选择商品名称'))
          return
        }
        if (col.amount == '') {
          that.$message.warning(that.$t('商品数量不能为空'))
          return
        }
        i++
      })
      // 触发表单验证
      if (i == that.dataSource.length) {
        that.$refs.form.validate((valid) => {
          if (valid) {
            param = that.model
            param.bisThirdGoodsPackageList=[]
            param.bisThirdGoodsPackageList = that.dataSource
            if(param.bisThirdGoodsPackageList.length==0){
              that.$message.warning(that.$t('至少添加一条卖品'))
              return
            }
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!that.model.id) {
              httpurl += that.url.add
              method = 'post'
            } else {
              httpurl += that.url.edit
              method = 'put'
            }
            httpAction(httpurl, param, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.close()
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      }
    },
    addGoods() {
      let obj = {
        goodsForm: undefined,
        goodsId: undefined,
        amount: 1,
      }
      this.dataSource.push(obj)
    },
    deleteGoods(a, b) {
      this.dataSource.forEach((col) => {
        if (col.goodsId == b.goodsId) {
          let index = this.dataSource.indexOf(col)
          this.dataSource.splice(index, 1)
        }
      })
    },
    handleFormChange(value,record) {
      record.goodsId=undefined
      this.getGoodsList(value)
    },
    handleGoodsSearch(form,value) {
      this.getGoodsList(form, value)
    },
    getFormList() {
      let that = this
      that.addFormList = []
      initDictOptions('bis_goods_infor.form').then((res) => {
        if (res.success) {
          that.addFormList = res.result.filter(rs=>{
            return rs.value!='5'&&rs.value!='6'&&rs.value!='7'&&rs.value!='11'&&rs.value!='13'&&rs.value!='16'
          })
        }
      })
    },
    getGoodsList(form, value) {
      this.addGoodsList = []
      let querydata = {}
      querydata.pageIndex = 1
      querydata.pageSize = 9999
      if(form){
        querydata.form = form
      }
      if(value){
        querydata.goodsInfo = value
      }
      getAction('/goods/bisGoodsInfor/list', querydata).then((res) => {
        if (res.success) {
          this.addGoodsList = res.result.records
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
  },
}
</script>